// components/up_video/up_video.js
const req=require("../../utils/request.js");
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    url:{
      type:"String",
      value:"http://localhost/php/getFile.php"
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    cover:"",
    video:"",
    timer:null,
    task:null,
    bg_opacty:"pbo1",
    default_img:"video_0.png",


    progress:0,
    loading:!1,
    show:!1,
    video_fd:!1,
    cover_fd:!1,
  },
  ready(){
    // this.showProgress();
  },
  attached(){
    let vd=wx.getStorageSync("temp_video");
    vd&&this.setData({
      cover: vd.cover || this.data.default_img,
      video:vd.video||""
    })
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //选择上传视频
    selVideo:function(){
      wx.chooseVideo({
        compressed:!1,
        success:res=>{
          console.log(res);
          this.setData({
            cover: res.thumbTempFilePath||"",
            video: res.tempFilePath||""
          });
          let param={};
          if (!res.tempFilePath) { return; } else { param = res.tempFilePath}
          if (res.thumbTempFilePath) {
            param=res.thumbTempFilePath;
            this.uploadCover(res.thumbTempFilePath);
          }
          this.triggerEvent('myselect',param);
          this.setData({
            loading:!0
          });
          let task=wx.uploadFile({
            url: this.properties.url,
            filePath: res.tempFilePath,
            name: 'file',
            success:res=>{
              console.log(res);
              if(res&&res.data){
                let r=JSON.parse(res.data);
                console.log(r);
                this.setData({
                  video: r.fileUrl||""
                });
                let vd=wx.getStorageSync("temp_video")||{};
                vd.video = r.fileUrl;
                wx.setStorageSync("temp_video", vd);
                this.triggerEvent("videofinish", {video: r.fileUrl});
              }else{
                this.loadError()
              }
            },
            fail:err=>{
              console.log(err);
              this.loadError()
            },
            complete:r=>{
              this.setData({
                loading: !1
              })
            }
          });
          this.setData({
            task: task
          })
          this.showProgress(task);
        }
      })
    },
    //上传进度
    showProgress:function(task){
      console.log(task);
      this.setData({
        task:task
      });
      task.onProgressUpdate(res => {
        // console.log('上传进度', res.progress)
        // console.log('已经上传的数据长度', res.totalBytesSent)
        // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
        this.setData({
          progress: res.progress,
        })
      });
      this.data.timer = setInterval(() => {
        this.setData({
          bg_opacty: this.data.bg_opacty == "pbo1" ? "pbo2" : "pbo1"
        });
        if (this.data.progress >= 100){
          clearInterval(this.data.timer);
        }
        console.log(this.data.progress)
      }, 1000)
    },
    //取消上传
    delThis:function(){
      let task=this.data.task;
      task.abort();
      clearInterval(this.data.timer);
      console.log(this.data.task,this.data.cover,this.data.video);
      this.this.loadError('上传被取消');
    },
    //测试按钮
    testShow:function(){
      this.setData({
        loading: !this.data.loading
      });
    },
    //更换封面
    handleThis:function(){
      wx.showActionSheet({
        itemList: ["更换封面","删除视频"],
        success: res=> {
          if(res.tapIndex==0){
            wx.chooseImage({
              count: 1,
              sizetype: ['original'],
              success: res => {
                let r = res.tempFiles[0];
                console.log(r,res);
                //限制图片大小
                if (r.size / 1024 < 500) {
                  this.uploadCover(r.path);
                } else {
                  if (app.globalData.imgN) {
                    wx.showToast({
                      title: '请小于500K',
                      image: app.globalData.imgN
                    })
                  }
                }
              }
            });
          }else if(res.tapIndex==1){
            this.delFinished();
          }
        },
      })
    },
    //清除已完成
    delFinished:function(){
      wx.showModal({
        title: '提示',
        content: '该视频已上传，您确定要删除吗？',
        success:res=>{
          if(res.confirm){
            this.setData({
              cover: "",
              video: ""
            });
            wx.removeStorageSync("temp_video");
          }
        }
      })
    },
    //上传封面
    uploadCover:function(cover){
      let img =cover||this.data.cover;
      wx.uploadFile({
        url: this.properties.url,
        filePath: img,
        name: 'file',
        success:res=>{
          console.log(res);
          if (res && res.data){
            let r=JSON.parse(res.data);
            this.setData({
              cover:r.fileUrl
            });
            let vd=wx.getStorageSync("temp_video", r.fileUrl)||{};
            vd.cover = r.fileUrl;
            wx.setStorageSync("temp_video", vd);
            this.triggerEvent("coverfinish", { cover: r.fileUrl });
          }else{
            wx.showToast({
              title: '封面上传失败',
              image:req.imgN
            })
          }
        },
        fail:err=>{
          console.log(err);
          wx.showToast({
            title: '封面上传失败',
            image: req.imgN
          })
        }
      });
    },
    //上传失败
    loadError:function(msg,icon){
      let param={};
      clearInterval(this.data.timer);
      param.title = msg || '上传失败';
      param.image=req.imgN;
      // if(icon){
      //   param.image=icon
      // }else{
      //   param.icon="loading"
      // }
      wx.showToast(param);
      this.setData({
        timer: null,
        task: null,
        cover: "",
        video: "",
        loading: !1
      });
    }
  }
})
